package com.eagle.ant.activity;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.preference.PreferenceManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.eagle.ant.R;
import com.eagle.ant.model.Forecast;
import com.eagle.ant.model.Weather;
import com.eagle.ant.util.HttpUtil;
import com.eagle.ant.util.Utility;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Name:
 * User: eagle
 * Date: 2020/1/7
 * Desc: 天气显示界面
 */
public class WeatherActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.id_title_city_textView)
    TextView mTitleCityTextView;
    @BindView(R.id.id_title_update_textView)
    TextView mTitleUpdateTextView;

    @BindView(R.id.id_degree_textView)
    TextView mDegreeTextView;
    @BindView(R.id.id_weather_info_textView)
    TextView mWeatherInfoTextView;

    @BindView(R.id.id_forecast_layout)
    LinearLayout mForecastLayout;
    @BindView(R.id.id_aqi_textView)
    TextView mAqiTextView;
    @BindView(R.id.id_pm25_textView)
    TextView mPm25TextView;

    @BindView(R.id.id_comfort_textView)
    TextView mComfortTextView;
    @BindView(R.id.id_car_wash_textView)
    TextView mCarWashTextView;
    @BindView(R.id.id_sport_textView)
    TextView mSportTextView;

    @BindView(R.id.id_weather_layout)
    ScrollView mWeatherLayout;
    @BindView(R.id.id_bing_imageView)
    ImageView mBingImageView;
    @BindView(R.id.id_refresh_layout)
    public SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;

    @BindView(R.id.id_drawer_layout)
    public DrawerLayout mDrawerLayout;

    private String mWeatherId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBar();
        setContentView(R.layout.activity_weather);
        ButterKnife.bind(this);

        initView();
    }

    /**
     * 部分数据初始化
     */
    private void initView() {
        mRefreshLayout.setOnRefreshListener(this);
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        mWeatherId = getIntent().getStringExtra("weather_id");

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = prefs.getString("weather", null);

        if (weatherString != null) {
            // 有缓存事直接解析天气数据
            Weather weather = Utility.handleWeatherResponse(weatherString);
            assert weather != null;

            if (mWeatherId.equals(weather.basic.weatherId)) {
                mWeatherId = weather.basic.weatherId;
                showWeatherInfo(weather);
            } else {
                requestWeather(mWeatherId);
            }
        } else {
            // 无缓存时去服务器查询天气
            mWeatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(mWeatherId);
        }
        String pic = prefs.getString("bing_pic", null);
        if (pic != null) {
            Glide.with(this).load(pic).into(mBingImageView);
        } else {
            loadBingPic();
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            mDrawerLayout.openDrawer(GravityCompat.START);
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 根据城市ID请求城市天气数据
     */
    public void requestWeather(String weatherId) {
        String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=35d5f85562494d95823b33619ef21b5c";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    Toast.makeText(WeatherActivity.this, "获取天气预报失败", Toast.LENGTH_SHORT).show();
                    mRefreshLayout.setRefreshing(false);
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = response.body().string();
                final Weather weather = Utility.handleWeatherResponse(data);
                runOnUiThread(() -> {
                    if (weather != null && "ok".equals(weather.status)) {
                        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                        editor.putString("weather", data);
                        editor.apply();
                        showWeatherInfo(weather);
                    } else {
                        Toast.makeText(WeatherActivity.this, "获取天气预报失败", Toast.LENGTH_SHORT).show();
                    }
                    mRefreshLayout.setRefreshing(false);
                });
            }
        });
        loadBingPic();
    }

    /**
     * 处理并展示Weather实体类中的数据
     */
    private void showWeatherInfo(Weather weather) {
        String cityName = weather.basic.cityName;
        String updateTime = weather.basic.update.updateTime.split(" ")[1];
        String degree = weather.now.temperature + "℃";
        String weatherInfo = weather.now.more.info;
        mTitleCityTextView.setText(cityName);
        mTitleUpdateTextView.setText(updateTime);
        mDegreeTextView.setText(degree);
        mWeatherInfoTextView.setText(weatherInfo);

        mForecastLayout.removeAllViews();
        for (Forecast forecast : weather.forecastList) {
            View view = LayoutInflater.from(this).inflate(R.layout.view_forecast_item, mForecastLayout, false);
            TextView dateText = view.findViewById(R.id.id_date_textView);
            TextView infoText = view.findViewById(R.id.id_info_textView);
            TextView maxText = view.findViewById(R.id.id_max_textView);
            TextView minText = view.findViewById(R.id.id_min_textView);

            dateText.setText(forecast.date);
            infoText.setText(forecast.more.info);
            maxText.setText(forecast.temperature.max);
            minText.setText(forecast.temperature.min);
            mForecastLayout.addView(view);
        }

        if (weather.aqi != null) {
            mAqiTextView.setText(weather.aqi.city.aqi);
            mPm25TextView.setText(weather.aqi.city.pm25);
        }

        String comfort = "舒适度：" + weather.suggestion.comfort.info;
        String carWash = "洗车指数：" + weather.suggestion.carWash.info;
        String sport = "运动指数：" + weather.suggestion.sport.info;

        mComfortTextView.setText(comfort);
        mCarWashTextView.setText(carWash);
        mSportTextView.setText(sport);
        mWeatherLayout.setVisibility(View.VISIBLE);
    }

    /**
     * 加载必应每日一图
     */
    private void loadBingPic() {
        String picUrl = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(picUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String pic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_pic", pic);
                editor.apply();
                runOnUiThread(() -> {
                    Glide.with(WeatherActivity.this).load(pic).into(mBingImageView);
                });
            }
        });
    }

    /**
     * 设置状态栏
     */
    private void setStatusBar() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    @Override
    public void onRefresh() {
        requestWeather(mWeatherId);
    }
}
